package com.shitou.shitouproduct.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.shitou.shitoucommons.utils.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shitou.shitoucommons.utils.PageUtils;
import com.shitou.shitoucommons.utils.Query;

import com.shitou.shitouproduct.dao.CategoryDao;
import com.shitou.shitouproduct.entity.CategoryEntity;
import com.shitou.shitouproduct.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    @Qualifier("RedisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * //优化前qps： 199
     * //优化后qps：1040
     * @return
     */
    @Override
    public RespBean queryTreeList() {

        String jasonString = (String) redisTemplate.opsForValue().get("allCategory");
        if ( jasonString != null && !jasonString.equals("") ){
            List<CategoryEntity> categoryEntities = (List<CategoryEntity>) JSON.parseArray(jasonString, CategoryEntity.class);
            if ( categoryEntities != null && categoryEntities.size() > 0 ){
                return RespBean.success().put("data", categoryEntities);
            }
        }
        // 获得所有的分类
        List<CategoryEntity> categoryList = this.list();

        // 递归查找
        List<CategoryEntity> menus = categoryList.stream().filter( categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map( categoryEntity -> {
            categoryEntity.setChildrenCategory(setChildrenList(categoryEntity, categoryList));
            return categoryEntity;
        }).sorted((category1, category2) ->{
            return (category1.getSort()==null?0:category1.getSort()) -
                    (category2.getSort()==null?0:category2.getSort());
        }).collect(Collectors.toList());

        // 第一次访问，存入redis中,并设置七天过期
        String jsonString = JSON.toJSONString(menus);
        redisTemplate.opsForValue().set("allCategory", jsonString, 7 ,TimeUnit.DAYS);

        return RespBean.success().put("data", menus);
    }


    /**
     * 递归查询
     * @param parentCategory
     * @param categoryList
     * @return
     */
    public List<CategoryEntity> setChildrenList(CategoryEntity parentCategory, List<CategoryEntity> categoryList){
        if ( parentCategory == null || categoryList == null){
            return null;
        }

        // 递归查询
        List<CategoryEntity> menus = categoryList.stream().filter( categoryEntity -> {
            return categoryEntity.getParentCid() == parentCategory.getCategoryId();
        }).map( categoryEntity -> {
            categoryEntity.setChildrenCategory(setChildrenList(categoryEntity, categoryList));
            return categoryEntity;
        }).sorted((category1, category2) ->{
            return (category1.getSort()==null?0:category1.getSort()) -
                    (category2.getSort()==null?0:category2.getSort());
        }).collect(Collectors.toList());

        return menus;
    }


    /**
     * 获取最上层的分类id
     * @return
     */
    @Override
    public RespBean info(Long categoryId) {
        CategoryEntity parent_id = this.getOne(new QueryWrapper<CategoryEntity>().eq("category_id", categoryId));
        if ( parent_id == null ){
            return RespBean.error();
        }
        return RespBean.success().put("category", parent_id);
    }

}
